//------------------------------------------------------------------------------
// The contents of this file are subject to the nopCommerce Public License Version 1.0 ("License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at  http://www.nopCommerce.com/License.aspx. 
// 
// Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. 
// See the License for the specific language governing rights and limitations under the License.
// 
// The Original Code is nopCommerce.
// The Initial Developer of the Original Code is NopSolutions.
// All Rights Reserved.
// 
// Contributor(s): _______. 
//------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using NopSolutions.NopCommerce.BusinessLogic;
using NopSolutions.NopCommerce.BusinessLogic.Events;
using NopSolutions.NopCommerce.BusinessLogic.Model;
using NopSolutions.NopCommerce.BusinessLogic.SEO;

namespace NopSolutions.NopCommerce.Web.Modules
{
    public partial class CheckoutShippingAddressControl : BaseNopFrontendUserControl
    {
        protected CheckoutStepChangedEventHandler handler;
        protected ShoppingCart cart = null;

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            Load += new EventHandler(OnLoad);

            rptShippingAddresses.ItemDataBound += new RepeaterItemEventHandler(rptShippingAddresses_ItemDataBound);
            btnNextStep.Click += new EventHandler(OnNextStepButtonClick);
            btnSelect.Click += new EventHandler(btnSelect_Click);
        }

        void OnLoad(object sender, EventArgs e)
        {
            if ((NopContext.Current.User == null) ||
                (
                    NopContext.Current.User.IsGuest &&
                    !this.CustomerService.AnonymousCheckoutAllowed)
                )
            {
                string loginURL = SEOHelper.GetLoginPageUrl(true);
                Response.Redirect(loginURL);
            }

            if (this.Cart.Count == 0)
                Response.Redirect(SEOHelper.GetShoppingCartUrl());
        }

        #region Properties

        protected Address ShippingAddress
        {
            get
            {
                var address = ctrlShippingAddress.Address;
                if (address.AddressId != 0 && NopContext.Current.User != null)
                {
                    var prevAddress = this.CustomerService.GetAddressById(address.AddressId);
                    if (prevAddress.CustomerId != NopContext.Current.User.CustomerId)
                        return null;
                    address.CustomerId = prevAddress.CustomerId;
                    address.CreatedOn = prevAddress.CreatedOn;
                }
                else
                {
                    address.CreatedOn = DateTime.UtcNow;
                }

                return address;
            }
        }

        protected List<Address> GetAllowedShippingAddresses(Customer customer)
        {
            var addresses = new List<Address>();
            if (customer == null)
                return addresses;

            foreach (var address in customer.ShippingAddresses)
            {
                var country = address.Country;
                if (country != null && country.AllowsShipping)
                {
                    addresses.Add(address);
                }
            }

            return addresses;
        }

        public ShoppingCart Cart
        {
            get
            {
                if (cart == null)
                {
                    cart = this.ShoppingCartService.GetCurrentShoppingCart(ShoppingCartTypeEnum.ShoppingCart);
                }
                return cart;
            }
        }

        public bool OnePageCheckout
        {
            get
            {
                if (ViewState["OnePageCheckout"] != null)
                    return (bool)ViewState["OnePageCheckout"];
                return false;
            }
            set
            {
                ViewState["OnePageCheckout"] = value;
            }
        }

        #endregion

        public void BindData()
        {
            bool shoppingCartRequiresShipping = this.ShippingService.ShoppingCartRequiresShipping(Cart);
            if (!shoppingCartRequiresShipping)
            {
                SelectAddress(null);
            }
            else
            {
                var addresses = GetAllowedShippingAddresses(NopContext.Current.User);
                if (addresses.Count > 0)
                {
                    rptShippingAddresses.DataSource = addresses;
                    rptShippingAddresses.DataBind();
                    lEnterShippingAddress.Text = GetLocaleResourceString("Checkout.OrEnterNewAddress");
                }
                else
                {
                    pnlSelectShippingAddress.Visible = false;
                    lEnterShippingAddress.Text = GetLocaleResourceString("Checkout.EnterShippingAddress");
                }
            }
        }

        protected void SelectAddress(Address shippingAddress)
        {
            if (shippingAddress == null)
            {
                //set default shipping address
                NopContext.Current.User.ShippingAddressId = 0;
                this.CustomerService.UpdateCustomer(NopContext.Current.User);

                var args1 = new CheckoutStepEventArgs() { ShippingAddressSelected = true };
                OnCheckoutStepChanged(args1);
                if (!this.OnePageCheckout)
                    Response.Redirect("~/checkoutbillingaddress.aspx");
                return;
            }

            if (shippingAddress.AddressId == 0)
            {
                //check if address already exists
                var shippingAddress2 = NopContext.Current.User.ShippingAddresses.FindAddress(shippingAddress.FirstName,
                    shippingAddress.LastName, shippingAddress.PhoneNumber, shippingAddress.Email,
                    shippingAddress.FaxNumber, shippingAddress.Company,
                    shippingAddress.FullAddress,
                    shippingAddress.City, shippingAddress.StateProvinceId, shippingAddress.ZipPostalCode,
                    shippingAddress.CountryId);

                if (shippingAddress2 != null)
                {
                    shippingAddress = shippingAddress2;
                }
                else
                {
                    shippingAddress.CustomerId = NopContext.Current.User.CustomerId;
                    shippingAddress.IsBillingAddress = false;
                    shippingAddress.CreatedOn = DateTime.UtcNow;
                    shippingAddress.UpdatedOn = DateTime.UtcNow;

                    this.CustomerService.InsertAddress(shippingAddress);
                }
            }

            //set default shipping address
            NopContext.Current.User.ShippingAddressId = shippingAddress.AddressId;
            this.CustomerService.UpdateCustomer(NopContext.Current.User);

            var args2 = new CheckoutStepEventArgs() { ShippingAddressSelected = true };
            OnCheckoutStepChanged(args2);
            if (!this.OnePageCheckout)
                Response.Redirect("~/checkoutbillingaddress.aspx");
        }

        protected virtual void OnCheckoutStepChanged(CheckoutStepEventArgs e)
        {
            if (handler != null)
            {
                handler(this, e);
            }
        }

        void rptShippingAddresses_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                var address = e.Item.DataItem as Address;
                if (address != null)
                {
                    var hfAddressId = e.Item.FindControl("hfAddressId") as HiddenField;
                    hfAddressId.Value = address.AddressId.ToString();

                    var litAddressName = e.Item.FindControl("litAddressName") as Literal;
                    var phCompany = e.Item.FindControl("phCompany") as PlaceHolder;

                    if (address.CompanyLegalForm)
                    {
                        litAddressName.Text = Server.HtmlEncode(address.Company);

                        phCompany.Visible = true;
                        var litCompany = e.Item.FindControl("litCompany") as Literal;

                        if (!string.IsNullOrWhiteSpace(address.CompanyFiscalCode))
                        {
                            litCompany.Text += Server.HtmlEncode(string.Format("{0} {1}", GetLocaleResourceString("Address.CompanyFiscalCode"), address.CompanyFiscalCode) + "; ");
                        }
                        if (!string.IsNullOrWhiteSpace(address.CompanyRegComNumber))
                        {
                            litCompany.Text += Server.HtmlEncode(string.Format("{0} {1}", GetLocaleResourceString("Address.CompanyFiscalCode"), address.CompanyRegComNumber) + "; ");
                        }
                        if (!string.IsNullOrWhiteSpace(address.CompanyBank))
                        {
                            litCompany.Text += Server.HtmlEncode(string.Format("{0} {1}", GetLocaleResourceString("Address.Company.Bank"), address.CompanyBank) + "; ");
                        }
                        if (!string.IsNullOrWhiteSpace(address.CompanyBankAccount))
                        {
                            litCompany.Text += Server.HtmlEncode(string.Format("{0} {1}", GetLocaleResourceString("Address.Company.BankAccount"), address.CompanyBankAccount) + "; ");
                        }
                    }
                    else
                    {
                        litAddressName.Text = Server.HtmlEncode(string.Format("{0} {1} ({2})", address.FirstName, address.LastName, address.Email));
                        phCompany.Visible = false;
                    }

                    // phones
                    var litPhoneNumbers = e.Item.FindControl("litPhoneNumbers") as Literal;
                    if (!string.IsNullOrWhiteSpace(address.PhoneNumber))
                    {
                        litPhoneNumbers.Text += Server.HtmlEncode(string.Format("{0} {1}", GetLocaleResourceString("Address.Phone"), address.PhoneNumber) + "; ");
                    }
                    if (!string.IsNullOrWhiteSpace(address.MobilePhoneNumber))
                    {
                        litPhoneNumbers.Text += Server.HtmlEncode(string.Format("{0} {1}", GetLocaleResourceString("Address.MobilePhone"), address.MobilePhoneNumber) + "; ");
                    }
                    if (!string.IsNullOrWhiteSpace(address.FaxNumber))
                    {
                        litPhoneNumbers.Text += Server.HtmlEncode(string.Format("{0} {1}", GetLocaleResourceString("Address.Fax"), address.FaxNumber) + "; ");
                    }

                    // address
                    var litAddress = e.Item.FindControl("litAddress") as Literal;
                    if (!string.IsNullOrWhiteSpace(address.FullAddress))
                    {
                        litAddress.Text += Server.HtmlEncode(string.Format("{0} {1}", GetLocaleResourceString("Address.Address1"), address.FullAddress) + "; ");
                    }
                    if (address.Country != null)
                    {
                        litAddress.Text += Server.HtmlEncode(string.Format("{0} {1}", GetLocaleResourceString("Address.Country"), address.Country.Name) + "; ");
                    }
                    if (!string.IsNullOrWhiteSpace(address.City))
                    {
                        litAddress.Text += Server.HtmlEncode(string.Format("{0} {1}", GetLocaleResourceString("Address.City"), address.City) + "; ");
                    }
                    if (address.StateProvince != null)
                    {
                        litAddress.Text += Server.HtmlEncode(string.Format("{0} {1}", GetLocaleResourceString("Address.StateProvince"), address.StateProvince.Name) + "; ");
                    }
                    if (!string.IsNullOrWhiteSpace(address.ZipPostalCode))
                    {
                        litAddress.Text += Server.HtmlEncode(string.Format("{0} {1}", GetLocaleResourceString("Address.ZipPostalCode"), address.ZipPostalCode) + "; ");
                    }
                }
            }
        }

        void btnSelect_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                //int addressId = int.Parse(e.CommandArgument.ToString());

                int addressId = -1;

                foreach (RepeaterItem item in rptShippingAddresses.Items)
                {
                    var rbAddress = item.FindControl("rbAddress") as RadioButton;
                    if (rbAddress != null && rbAddress.Checked)
                    {
                        var hfAddressId = item.FindControl("hfAddressId") as HiddenField;
                        addressId = int.Parse(hfAddressId.Value);
                    }
                }

                var shippingAddress = this.CustomerService.GetAddressById(addressId);
                if (shippingAddress != null && NopContext.Current.User != null)
                {
                    var prevAddress = this.CustomerService.GetAddressById(shippingAddress.AddressId);
                    if (prevAddress.CustomerId != NopContext.Current.User.CustomerId)
                        return;
                }

                SelectAddress(shippingAddress);
            }
        }

        protected void OnNextStepButtonClick(object sender, EventArgs e)
        {
            Page.Validate("EnterShippingAddress");
            if (Page.IsValid)
            {
                var shippingAddress = this.ShippingAddress;
                SelectAddress(shippingAddress);
            }
        }

        public event CheckoutStepChangedEventHandler CheckoutStepChanged
        {
            add { handler += value; }
            remove { handler -= value; }
        }
    }
}